package com.xmg.p2p.base.service.impl;

import java.util.Date;

import com.xmg.p2p.base.mapper.IplogMapper;
import com.xmg.p2p.base.service.AccountService;
import com.xmg.p2p.base.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xmg.p2p.base.domain.Account;
import com.xmg.p2p.base.domain.Iplog;
import com.xmg.p2p.base.domain.Logininfo;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.LogininfoMapper;
import com.xmg.p2p.base.service.ILogininfoService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.MD5;
import com.xmg.p2p.base.util.UserContext;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Andy
 */
@Service
public class LogininfoServiceImpl implements ILogininfoService {
//    登录页面
	private LogininfoMapper  logininfoMapper;
	@Autowired
	public void setLogininfoMapper(LogininfoMapper logininfoMapper) {
		this.logininfoMapper = logininfoMapper;
	}
//    用户信息
	private AccountService accountService;
	@Autowired
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
//	  账户信息
	private UserinfoService userinfoService;
	@Autowired
	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}
//    登录日志信息
    private IplogMapper iplogMapper;
    @Autowired
    public void setIplogMapper(IplogMapper iplogMapper) {
        this.iplogMapper = iplogMapper;
    }

    /**注册*/
	public void register(String username, String password) {
		// 判断昵称是否存在
		int ret = logininfoMapper.countUserByName(username);
		if(ret <= 0){
			// 保存数据
			Logininfo logininfo = new Logininfo();
			logininfo.setUsername(username);
			logininfo.setPassword(MD5.encode(password));
			logininfo.setState(Logininfo.STATE_NORMAL);
			logininfo.setUserType(Logininfo.USER_CLIENT);
			logininfoMapper.insert(logininfo);
			// 初始化账号信息
			Account account = new Account();
			account.setId(logininfo.getId());
			this.accountService.add(account);
			// 初始化用户信息
			Userinfo userinfo = new Userinfo();
			userinfo.setId(logininfo.getId());
			this.userinfoService.add(userinfo);
		}else{
			throw new RuntimeException("用户名已注册！");
		}
	}
	/**判断用户是否存在*/
	public boolean checkUserNameExist(String username) {
		int ret = logininfoMapper.countUserByName(username);
		if (ret > 0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 前端的登录业务
	 * @param username	// 用户名
	 * @param password	// 密码
	 * @param ip		// 登录的IP地址
	 * @param userType	// 用户类型（前端用户\后端用户）
	 * @return
	 */
	public Logininfo login(String username, String password,String ip,int userType) {
        /*因为在注册的时候密码使用了MD5进行了加密,所以在查询的时候,需要使用MD5加密后比较*/
		Logininfo logininfo = logininfoMapper.login(username,MD5.encode(password),userType);

		// 创建日志对象
        Iplog iplog = new Iplog();
        iplog.setIp(ip);
        iplog.setLoginTime(new Date());
        iplog.setUserName(username);
        iplog.setUserType(userType);

		if(logininfo != null){
//		    将登录的信息保存到Session中，使用UserContext工具类
			UserContext.putCurrent(logininfo);
			iplog.setState(Iplog.STATE_SUCCESS);	// 登录成功的状态
		}else {
            iplog.setState(Iplog.STATE_FAILED);		// 登录失败的状态

		}
		HttpSession session = UserContext.getSession();
		Date date = this.endLoginTime();
		session.setAttribute("datetime",date);
        iplogMapper.insert(iplog);
		return logininfo;
	}

	public void initAdmin() {
		// 查询是否有管理员：
		int count = this.logininfoMapper.countByUserType(Logininfo.USER_MANAGER);
		// 如果没有就创建一个默认的管理员
		if (count == 0){
			Logininfo admin = new Logininfo();
			// BidConst 常量工具类，其中包含了 管理员的 账号 和 密码
			// 密码在使用的时候，需要进行加密操作
			admin.setUsername(BidConst.DEFAULT_ADMIN_NAME);
			admin.setPassword(MD5.encode(BidConst.DEFAULT_ADMIN_PASSWORD));
			// 账号的一个状态，一般情况下，刚创建的账号都是正常的、
			admin.setState(Logininfo.STATE_NORMAL);
			admin.setUserType(Logininfo.USER_MANAGER);
			this.logininfoMapper.insert(admin);

		}
	}
	public Date endLoginTime() {
		Date date = logininfoMapper.endLoginTime(UserContext.getCurrent().getUsername());
		return date;
	}
}
